package com.sample.trace.aop;

import com.sample.trace.bean.MDCParam;
import com.sample.trace.config.TraceProperties;
import com.sample.trace.utils.MDCUtil;
import com.sample.trace.utils.TraceLocalUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

/**
 * RabbitMQ traceId 生成
 */
@Aspect
@Component
@Order(0)
public class RabbitTraceAspect {

    @Resource
    private TraceProperties traceProperties;

    @Pointcut("@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Map<String, Object> localMap = TraceLocalUtil.getMap();
            if (localMap == null) {
                MDCUtil.clear();
                MDCParam param = new MDCParam();
                param.setTraceId(UUID.randomUUID().toString());
                param.setServerName(traceProperties.getServerName());
                //TODO upServer
                param.setUpServer(traceProperties.getServerName());
                MDCUtil.put(param);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object result = joinPoint.proceed();
        // 清除TreadLocal MDC
        MDCUtil.clear();
        return result;
    }

}

